import { PageDto } from "../../models/page.model";
import { UaIpEntity } from "../../models/ua-ip.model";
import { UaUserDeckEntity, UaUserDeckSearchDto } from "../../models/ua-user-deck.model";
import { GlobalService } from "../../services/global.service";
import { UaIpService } from "../../services/ua-ip.service";
import { UserDeckService } from "../../services/ua-user-deck.service";
import { formatDate } from "../../utils/util";

// pages/lobby/lobby.page.ts
Page({
  /**
   * 页面的初始数据
   */
  data: {
    CDN_HOST: GlobalService.FILE_HOST,
    FILE_HOST: GlobalService.STATIC_ASSETS_HOST,
    ipList: [] as { label: string, value: number }[],
    ipLogoMap: {} as { [key: number]: string },
    deckList: [] as UaUserDeckEntity[],
    popupVisible: false,
    hasMore: true,
    TIER1: '/marketing/tier1.png',
    TIER2: '/marketing/tier2.png',
    previewDeckId: 0,
  },

  customData: {
    page: 1,
    totalPage: 1,
    searchRequest: {} as UaUserDeckSearchDto
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    wx.setNavigationBarTitle({
      title: '卡组广场'
    });
    UaIpService.fetchUaIpList().then((response: UaIpEntity[]) => {
      const ipList: { label: string, value: number }[] = [];
      const ipLogoMap: { [key: number]: string } = {};
      for (const ip of response) {
        ipList.push({
          label: ip.ipTitleCn!,
          value: ip.id!
        });
        ipLogoMap[ip.id!] = ip.ipTitleLogo!;
      }
      this.setData({
        ipList,
        ipLogoMap,
      });
      this.load();
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getTabBar().setData({
      value: '/pages/lobby/lobby'
    });
    this.setData({
      previewDeckId: 0
    })
    this.customData.page = 1;
    this.load();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.customData.page = 1;
    this.load();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.customData.page >= this.customData.totalPage) {
      return;
    }
    this.customData.page++;
    this.load();
  },

  load() {
    UserDeckService.searchWithPage(this.customData.searchRequest, this.customData.page).then((response: PageDto<UaUserDeckEntity>) => {
      this.customData.totalPage = response.meta!.pageCount!;
      for (const item of response.data ?? []) {
        const date = new Date(item.updateDate ?? Date.now());
        if (!!item.cover) {
          item.coverCardList = item.cover.split(';');
        } else {
          item.coverCardList = [];
        }
        item.updateDateStr = formatDate(date);
        if (item.mainEnergyType) {
          item.mainEnergyTypeLogo = `/jp/images/cardlist/icon/resource/ico_resource_energy_${item.mainEnergyType?.toLowerCase()}1.png`;
        }
      }
      if (this.customData.page === 1) {
        this.setData({
          deckList: response.data,
          hasMore: this.customData.page < this.customData.totalPage
        })
      } else {
        this.setData({
          deckList: [...this.data.deckList, ...response.data!],
          hasMore: this.customData.page < this.customData.totalPage
        })
      }
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  onChoose(e: any) {
    // const index = e.currentTarget.dataset.index;
    // const deck = this.data.deckList[index];
    // console.log(this.data.deckList);
    console.log(e.currentTarget.dataset)
    this.setData({
      previewDeckId: e.currentTarget.dataset['id']
    })
  },

  deckDetail(e: any) {
    wx.navigateTo({
      url: `/pages/user/user-deck-detail/user-deck-detail.page?ipId=${e.currentTarget.dataset['ipid']}&deckId=${e.currentTarget.dataset['id']}`,
    });
  },

  sheet(e: any) {
    wx.navigateTo({
      url: `/pages/tools/deck-sheet/deck-sheet.page?ipId=${e.currentTarget.dataset['ipid']}&deckId=${e.currentTarget.dataset['id']}`,
    });
  },

  onDelete(e: any) {
    const index = e.currentTarget.dataset.index;
    const deck = this.data.deckList[index];
    wx.showModal({
      title: '是否删除？',
      confirmText: "删除",
      cancelText: "取消",
      showCancel: true,
      confirmColor: "#eb445a",
      success: (res) => {
        if (res.confirm) {
          this.removeDeck(deck);
        }
      }
    });
  },

  removeDeck(deck: UaUserDeckEntity) {
    UserDeckService.removeById(deck.id!).then(() => {
      this.onShow();
    })
  },

  filter() {
    this.setData({
      popupVisible: true
    })
  },

  onPopupVisibleChange(e: any) {
    this.setData({
      popupVisible: e.detail.visible
    });
  },

  onReset(e: any) {
    this.customData.searchRequest = e.detail;
  },

  onSearch(e: any) {
    console.log(e)
    this.setData({
      popupVisible: false
    });
    this.customData.searchRequest = e.detail;
    this.onPullDownRefresh();
  },


  test(e: any) {
    wx.showActionSheet({
      itemList: ['内战模拟', '对战模拟', '(旧版)抽牌模拟'],
      success: (res) => {
        switch (res.tapIndex) {
          case 0:
            this.deckTest(e)
            break;
          case 1:
            this.battleTest(e);
            break;
          case 2:
            this.drawTest(e);
            break;
        }
      },
      fail: () => { }
    })
  },


  drawTest(e: any) {
    wx.navigateTo({
      url: `/pages/user/deck-test/deck-test.page?deckId=${e.currentTarget.dataset['id']}`,
    });
  },


  deckTest(e: any) {
    wx.navigateTo({
      url: `/pages/user/deck-battle-test/deck-battle-test.page?deckId1=${e.currentTarget.dataset['id']}`,
    });
  },

  battleTest(e: any) {
    wx.navigateTo({
      url: `/pages/user/user-deck-list/user-deck-list.page?deckId=${e.currentTarget.dataset['id']}`,
    });
  }

})